package com.qf.qfmanagergateway.filters;

import com.qf.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

@Component
@Order(-5)
@Slf4j
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取当前访问的资源路径
        String uri = request.getURI().toString();
        log.info("---uri: {}",uri);

        if (uri.contains("/user/")){
            //访问的是user-manager服务，这个登录认证交给服务本身处理
            //放行
            return chain.filter(exchange);
        }

        if (uri.contains("/auth/tenant/login")){
            //表示访问的是tenant-manager服务的登录接口
            //放行
            return chain.filter(exchange);
        }

        //认证
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)){
            token = request.getQueryParams().getFirst("token");
        }

        if (StringUtils.isEmpty(token) || "null".equals(token)){
            //没有携带 - 提示去登录
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //验证token的合法性
        try {
            Claims claims = JwtUtil.parseJWT(token);
        }catch (ExpiredJwtException expire){
            //有效时间
            long time = expire.getClaims().getExpiration().getTime();
            long permitTime = System.currentTimeMillis()+1000*60*30;

            if (time <= permitTime){
                //允许复活
                String newJwt = JwtUtil.createJWT(UUID.randomUUID().toString().replaceAll("-", ""),
                        expire.getClaims().getSubject(),
                        null
                );

                //要将新的jwt返回到页面端
                response.getHeaders().set("refresh_token",newJwt);
            }else{
                expire.printStackTrace();
                //过期
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        return chain.filter(exchange);
    }
}
